package middleware

import (
	"gin-vue/common"
	"gin-vue/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthMiddleWare() gin.HandlerFunc {

	return func(context *gin.Context) {
		//获取请求头
		tokenString := context.GetHeader("Authorization")
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401})
			context.Abort()
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401})
			context.Abort()
			return
		}

		//验证通过，获取user id
		userID := claims.UserId
		DB := common.GetDB()
		var user model.User
		DB.First(&user, userID)

		if user.ID == 0 {
			context.JSON(http.StatusUnauthorized, gin.H{"code": 401})
			context.Abort()
			return
		}
		context.Set("user", user)
		context.Next()
	}
}
